package com.kakarote.crm9.erp.ding.cron;



import com.kakarote.crm9.erp.ding.entity.AppId;
import com.kakarote.crm9.erp.ding.entity.DingToken;
import com.kakarote.crm9.erp.ding.service.AppidService;
import com.kakarote.crm9.erp.ding.service.DingTokenService;
import com.kakarote.crm9.utils.HttpUtils;
import net.sf.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class DingCron implements Runnable {

    private static AppidService appidService = new AppidService();
    private static DingTokenService dingTokenService = new DingTokenService();
    @Override
    public void run() {
        AppId appId = appidService.get("1");
        upToken(appId,"1");
        AppId appId2 = appidService.get("2");
        upToken(appId2,"2");
    }

    public void upToken(AppId appId,String token_id){
        Map<String,String> map = new HashMap<>();
        map.put("app_id",appId.getAppId());
        map.put("secret_key",appId.getSecretKey());
        HttpUtils httpUtils = new HttpUtils();
        String result = httpUtils.doGet(appId.getUrl(),map,null);
        JSONObject object = JSONObject.fromObject(result);
        String acc = object.getJSONObject("data").getString("access_token");
        DingToken dingToken = dingTokenService.get(token_id);
        dingToken.setAccessToken(acc);
        dingToken.setUpdateDate(new Date());
        dingToken.update();
    }
}
